<template>
  <a-modal v-model:visible="visible" draggable :width="width" @cancel="handleCancel">
    <a-upload
      ref="uploadRef"
      draggable
      :action="action"
      :headers="headers"
      :auto-upload="false"
      :show-file-list="true"
      :limit="1"
      @change="onChange"
      @success="uploadSuccess"
    />
    <div class="tip">
      <span class="label">仅允许导入xls、xlsx格式文件。</span>
      <a-link class="download" @click="downloadTemplate">{{ $t('operations.export.template') }}</a-link>
    </div>
    <template #footer>
      <a-button
        style="margin-right: 8px"
        @click="handleCancel"
      >{{ $t('searchTable.columns.operations.close') }}</a-button>
      <a-button
        type="primary"
        @click="handleSubmit"
        :loading="loading"
      >{{ $t('searchTable.columns.operations.confirm') }}</a-button>
    </template>
  </a-modal>
</template>
  <script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';

const { t } = useI18n();

const loading = ref(false);
const visible = ref(false);
const width = ref('calc(30%)');

// 触发父组件事件 刷新用户列表
const emit = defineEmits({ onSearch: null, downloadTemplate: null });

const props = withDefaults(
  defineProps<{
    url?: string;
  }>(),
  {
    url: '/common/file/upload', // 默认值
  }
);

// 上传地址
const action = ref(import.meta.env.VITE_API_BASE_URL + props.url); 
const headers = ref({ Authorization: 'Bearer ' + getToken() });
const uploadRef = ref();
const files = ref([]);

// 打开弹窗
const onOpen = async () => {
  visible.value = true;
};

// 下载模版
const downloadTemplate = () => {
  emit('downloadTemplate');
};

// 上传文件成功
const uploadSuccess = (resp: any) => {
  const res = resp.response;
  if (res.code != 200) {
    Message.error(res.msg);
    loading.value = false;
    return;
  }
  const data = res.data;
  loading.value = false;
  onOk();
};

const onChange = (fileList) => {
  files.value = fileList;
};

// 确认
const handleSubmit = async (e) => {
  e.stopPropagation();
  uploadRef.value.submit();
  loading.value = true;
};

// 确认
const onOk = () => {
  visible.value = false;
  Message.success(t('operations.import.success'));
  emit('onSearch');
};

// 取消
const handleCancel = () => {
  onCancel();
};

// 取消
const onCancel = () => {
  visible.value = false;
};

// 抛出函数
defineExpose({
  onOpen,
});
</script>
<style scoped lang="less">
:deep(.arco-upload-progress) {
  display: none;
}
.tip {
  display: flex;
  justify-content: center;
  margin: 10px 0px;
  font-size: 13px;
  .download {
    cursor: pointer;
  }
}
</style>